package org.dmikis.task11.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import javax.swing.*;

import org.dmikis.task11.PhasePoint;
import org.dmikis.task11.engine.EulerEngine;
import org.dmikis.task11.engine.RungeKuttEngine;


public class MainWindow extends JFrame {

    public MainWindow() {
	super();
	this.setTitle("Task 11");
	this.setSize(MainWindow.DEFAILT_WIDTH, MainWindow.DEFUALT_HEIGHT);
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	this.setMinimumSize(new Dimension(MainWindow.DEFAILT_WIDTH, MainWindow.DEFUALT_HEIGHT));
	EulerEngine e = (EulerEngine) EulerEngine.getInstance();
	e.setStartingPoint(new PhasePoint(1.0, 0.25*Math.PI, 0.0));
	e.setErrorValue(0.1);
	e.run();
	try {
	    PrintWriter p = new PrintWriter("test.txt");
	    double[] timeline = e.getTimeline();
	    for (double time : timeline) {
		p.println(e.getPoint(time));
	    }
	    p.close();
	}
	catch (Exception ex) {
	    System.err.println(ex.getMessage());
	}
	_panel.setEngine(e);
	this.add(_panel);
	JPanel button_panel = new JPanel();
	JButton euler_button = new JButton("Эйлер");
	euler_button.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent arg0) {
		EulerEngine e = (EulerEngine) EulerEngine.getInstance();
		e.setStartingPoint(new PhasePoint(1.0, 0.25*Math.PI, 0.0));
		e.setErrorValue(0.1);
		e.run();
		try {
		    PrintWriter p = new PrintWriter("test.txt");
		    double[] timeline = e.getTimeline();
		    for (double time : timeline) {
			p.println(e.getPoint(time));
		    }
		    p.close();
		}
		catch (Exception ex) {
		    System.err.println(ex.getMessage());
		}
		_panel.setEngine(e);
		_panel.repaint();
	    }
	});
	button_panel.add(euler_button);
	JButton rk_button = new JButton("Рунге-Кутт");
	rk_button.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent arg0) {
		RungeKuttEngine e = (RungeKuttEngine) RungeKuttEngine.getInstance();
		e.setStartingPoint(new PhasePoint(1.0, 0.25*Math.PI, 0.0));
		e.setErrorValue(0.1);
		e.run();
		try {
		    PrintWriter p = new PrintWriter("test.txt");
		    double[] timeline = e.getTimeline();
		    for (double time : timeline) {
			p.println(e.getPoint(time));
		    }
		    p.close();
		}
		catch (Exception ex) {
		    System.err.println(ex.getMessage());
		}
		_panel.setEngine(e);
		_panel.repaint();
	    }
	});
	button_panel.add(rk_button);
	this.add(button_panel, BorderLayout.NORTH);
    }
    
    private GraphPanel _panel = new GraphPanel();
    
    private static final int DEFAILT_WIDTH = 640; // px
    private static final int DEFUALT_HEIGHT = 480; // px
    
    private static final long serialVersionUID = 1L;

}
